import { useState, useEffect, useRef } from 'react'
import { View, ScrollView, Canvas } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import * as uCharts from '../../js_sdk/u-charts.min.js'
import './index.scss'

// 定义账单数据类型
interface BillRecord {
  amount: string
  type: string | number
  selectedType: string
  remarks: string
  date: string
  selectedIcon: string
  id: string
}

// 定义统计数据类型
interface MonthStats {
  month: string
  income: number
  expense: number
}

const Discover = () => {
  const STORAGE_KEY = 'bill_records'
  const [list, setList] = useState<BillRecord[]>([])
  const [monthlyStats, setMonthlyStats] = useState<MonthStats[]>([])
  const canvasId = 'billChart'
  const chartInstanceRef = useRef<any>(null)

  // 主题：light | dark
  const [theme, setTheme] = useState<'light' | 'dark'>(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      return cached === 'dark' ? 'dark' : 'light'
    } catch {
      return 'light'
    }
  })

  // 组件加载时读取数据
  useEffect(() => {
    loadBillRecords()
  }, [])

  useDidShow(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      setTheme(cached === 'dark' ? 'dark' : 'light')
    } catch {}
  })

  // 从本地存储加载账单记录
  const loadBillRecords = async () => {
    try {
      const data = await Taro.getStorage({ key: STORAGE_KEY })
      if (data.data) {
        const records = JSON.parse(data.data)
        setList(records)
        calculateMonthlyStats(records)
      }
    } catch (error) {
      console.log('暂无账单记录')
      setList([])
    }
  }

  // 计算每月统计数据
  const calculateMonthlyStats = (records: BillRecord[]) => {
    const statsMap = new Map<string, { income: number; expense: number }>()

    records.forEach(record => {
      const date = new Date(record.date)
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`

      if (!statsMap.has(monthKey)) {
        statsMap.set(monthKey, { income: 0, expense: 0 })
      }

      const stats = statsMap.get(monthKey)!
      const amount = parseFloat(record.amount)

      if (record.type === '0') {
        stats.income += amount
      } else {
        stats.expense += amount
      }
    })

    // 转换为数组并按月份排序
    const statsArray = Array.from(statsMap.entries())
      .map(([month, data]) => ({
        month,
        income: data.income,
        expense: data.expense
      }))
      .sort((a, b) => b.month.localeCompare(a.month)) // 倒序排列
      .slice(0, 6) // 只显示最近6个月

    setMonthlyStats(statsArray)
  }

  // 使用 useEffect 监听数据变化并初始化图表
  useEffect(() => {
    if (monthlyStats.length > 0) {
      initChart(monthlyStats)
    }
  }, [monthlyStats])

  // 初始化图表配置 - 多端兼容
  const initChart = (data: MonthStats[]) => {
    setTimeout(() => {
      const sysInfo = Taro.getSystemInfoSync()
      const pixelRatio =  1
      const platform = Taro.getEnv()

      console.log('当前平台:', platform)

      // H5 环境使用不同的初始化方式
      if (platform === 'WEB') {
        // H5 使用普通 Canvas API
        let canvasEl = document.getElementById(canvasId) as HTMLCanvasElement
        
        // Taro 的 Canvas 组件可能被包装，需要查找实际的 canvas 元素
        if (canvasEl && canvasEl.tagName !== 'CANVAS') {
          const realCanvas = canvasEl.querySelector('canvas')
          if (realCanvas) {
            canvasEl = realCanvas as HTMLCanvasElement
          }
        }
        
        if (!canvasEl || canvasEl.tagName !== 'CANVAS') {
          console.error('Canvas元素未找到或类型不正确')
          return
        }

        console.log('Canvas元素:', canvasEl)
        console.log('Canvas标签名:', canvasEl.tagName)
        
        // 从父容器或样式获取尺寸
        const parentEl = canvasEl.parentElement
        const canvasWidth = parentEl ? parentEl.clientWidth : 700
        const canvasHeight = 500
        const ctx = canvasEl.getContext('2d')
        
        if (!ctx) {
          console.error('无法获取 Canvas 2D 上下文')
          return
        }

        console.log('H5 Canvas尺寸:', { width: canvasWidth, height: canvasHeight })
        console.log('图表数据:', data)

        // 设置 Canvas 实际分辨率
        canvasEl.width = canvasWidth * pixelRatio
        canvasEl.height = canvasHeight * pixelRatio
        canvasEl.style.width = canvasWidth + 'px'
        canvasEl.style.height = canvasHeight + 'px'
        ctx.scale(pixelRatio, pixelRatio)

        const chartConfig = {
          type: 'column',
          context: ctx,
          width: canvasWidth,
          height: canvasHeight,
          categories: data.map(item => item.month.slice(5) + '月'),
          series: [
            {
              name: '收入',
              data: data.map(item => Number(item.income.toFixed(2)))
            },
            {
              name: '支出',
              data: data.map(item => Number(item.expense.toFixed(2)))
            }
          ],
          pixelRatio: 1,
          animation: true,
          background: '#FFFFFF',
          color: ['#52c41a', '#ff4d4f'],
          dataLabel: true,
          dataPointShape: true,
    
          legend: {
            show: true
          },
          xAxis: {
            disableGrid: false,
            scrollShow: true,
            scrollAlign: 'left'
          },
          yAxis: {
            gridType: 'dash',
            dashLength: 2,
            data: [{
              min: 0
            }]
          },
          extra: {
            column: {
              type: 'group',
              width: 15,
              activeBgColor: '#000000',
              activeBgOpacity: 0.08
            }
          }
        }

        try {
          chartInstanceRef.current = new uCharts.default(chartConfig)
          console.log('H5 图表实例创建成功')
        } catch (error) {
          console.error('H5 创建图表失败:', error)
        }
      } else {
        // 小程序环境使用 Canvas 2D API
        const query = Taro.createSelectorQuery()
        query.select(`#${canvasId}`)
          .fields({ node: true, size: true })
          .exec((res) => {
            console.log('小程序 Canvas查询结果:', res)
            if (!res || !res[0] || !res[0].node) {
              console.error('Canvas节点获取失败:', res)
              return
            }

            const { node: canvas, width: canvasWidth, height: canvasHeight } = res[0]

            if (canvasWidth && canvasHeight) {
              const ctx = canvas.getContext('2d')

              console.log('小程序 Canvas尺寸:', { width: canvasWidth, height: canvasHeight, pixelRatio })
              console.log('图表数据:', data)

              canvas.width = canvasWidth * pixelRatio
              canvas.height = canvasHeight * pixelRatio
              ctx.scale(pixelRatio, pixelRatio)

              const chartConfig = {
                type: 'column',
                context: ctx,
                width: canvasWidth,
                height: canvasHeight,
                categories: data.map(item => item.month.slice(5) + '月'),
                series: [
                  {
                    name: '收入',
                    data: data.map(item => Number(item.income.toFixed(2)))
                  },
                  {
                    name: '支出',
                    data: data.map(item => Number(item.expense.toFixed(2)))
                  }
                ],
                pixelRatio: pixelRatio,
                animation: true,
                background: '#FFFFFF',
                color: ['#52c41a', '#ff4d4f'],
                dataLabel: true,
                dataPointShape: true,
                legend: {
                  show: true
                },
                xAxis: {
                  disableGrid: false,
                  scrollShow: true,
                  scrollAlign: 'left'
                },
                yAxis: {
                  gridType: 'dash',
                  dashLength: 2,
                  data: [{
                    min: 0
                  }]
                },
                extra: {
                  column: {
                    type: 'group',
                    width: 15,
                    activeBgColor: '#000000',
                    activeBgOpacity: 0.08
                  }
                }
              }

              try {
                chartInstanceRef.current = new uCharts.default(chartConfig)
                console.log('小程序图表实例创建成功')
              } catch (error) {
                console.error('小程序创建图表失败:', error)
              }
            }
          })
      }
    }, 300)
  }

  // 处理图表点击事件
  const handleTouchEnd = (e) => {
    if (chartInstanceRef.current) {
      chartInstanceRef.current.showToolTip(e)
    }
  }

  // 计算总收入和总支出
  const calculateTotal = () => {
    let totalIncome = 0
    let totalExpense = 0

    list.forEach(record => {
      const amount = parseFloat(record.amount)
      if (record.type === '0') {
        totalIncome += amount
      } else {
        totalExpense += amount
      }
    })

    return { totalIncome, totalExpense }
  }

  const { totalIncome, totalExpense } = calculateTotal()
  const balance = totalIncome - totalExpense

  return (
    <View className={`discover-page ${theme === 'dark' ? 'theme-dark' : 'theme-light'}`}>
      <View className="discover-header">
        <View className="header-title">数据统计</View>
      </View>

      {/* 总览卡片 */}
      <View className="overview-card">
        <View className="overview-item">
          <View className="overview-label">总收入</View>
          <View className="overview-value income">¥{totalIncome.toFixed(2)}</View>
        </View>
        <View className="overview-item">
          <View className="overview-label">总支出</View>
          <View className="overview-value expense">¥{totalExpense.toFixed(2)}</View>
        </View>
        <View className="overview-item">
          <View className="overview-label">结余</View>
          <View className={`overview-value ${balance >= 0 ? 'income' : 'expense'}`}>
            ¥{balance.toFixed(2)}
          </View>
        </View>
      </View>

      {/* 月度统计 */}
      <View className="stats-section">
        <View className="section-title">月度统计</View>

        <ScrollView scrollY className="month-list">
          {monthlyStats.length === 0 ? (
            <View className="empty-state">暂无数据</View>
          ) : (
            monthlyStats.map((stat, index) => {
              const monthBalance = stat.income - stat.expense
              return (
                <View key={index} className="month-item">
                  <View className="month-header">
                    <View className="month-name">{stat.month}</View>
                    <View className={`month-balance ${monthBalance >= 0 ? 'positive' : 'negative'}`}>
                      {monthBalance >= 0 ? '+' : ''}{monthBalance.toFixed(2)}
                    </View>
                  </View>
                  <View className="month-details">
                    <View className="detail-item">
                      <View className="detail-label">收入</View>
                      <View className="detail-value income">¥{stat.income.toFixed(2)}</View>
                    </View>
                    <View className="detail-item">
                      <View className="detail-label">支出</View>
                      <View className="detail-value expense">¥{stat.expense.toFixed(2)}</View>
                    </View>
                  </View>
                </View>
              )
            })
          )}
        </ScrollView>
      </View>

      {/* 图表展示 */}
      {monthlyStats.length > 0 && (
        <View className="chart-section">
          <View className="section-title">月度趋势图</View>
          <View className="chart-container">
            <Canvas
              canvasId={canvasId}
              id={canvasId}
              type='2d'
              className="charts"
              style={{ width: '100%', height: '500px' }}
              onTouchEnd={handleTouchEnd}
            />
          </View>
        </View>
      )}

      {/* 数据概览 */}
      <View className="data-summary">
        <View className="summary-title">数据概览</View>
        <View className="summary-grid">
          <View className="summary-item">
            <View className="summary-label">记账天数</View>
            <View className="summary-value">{calculateDays()}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">记录笔数</View>
            <View className="summary-value">{list.length}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">日均支出</View>
            <View className="summary-value">¥{calculateAvgExpense()}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">日均收入</View>
            <View className="summary-value">¥{calculateAvgIncome()}</View>
          </View>
        </View>
      </View>
    </View>
  )

  // 计算记账天数
  function calculateDays(): number {
    if (list.length === 0) return 0

    const dates = new Set(
      list.map(record => new Date(record.date).toLocaleDateString('zh-CN'))
    )
    return dates.size
  }

  // 计算日均支出
  function calculateAvgExpense(): string {
    const days = calculateDays()
    if (days === 0) return '0.00'
    return (totalExpense / days).toFixed(2)
  }

  // 计算日均收入
  function calculateAvgIncome(): string {
    const days = calculateDays()
    if (days === 0) return '0.00'
    return (totalIncome / days).toFixed(2)
  }
}

export default Discover